﻿package com.thaiflashdev.utils
{
	import flash.events.Event;
	import flash.text.TextField;
	
	public class WmodeFix
	{
		/**
		 * @example
		 * WmodeFix.fix(textfield);
		 * 
		 * @author	keerotic
		 */	
		public static function fix(ti:TextField):void
		{
			ti.addEventListener(Event.CHANGE,doFix);
		}

		private static function doFix(e:Event):void
		{
			var ti:TextField = e.currentTarget as TextField;
			
			var str:String = ti.text;
			var cursor:int = ti.selectionEndIndex;
			var len:int = str.length;
			if (len > 0) 
			{
				for (var i:int = 0; i< len; i++) 
				{
					var code1:Number = str.charCodeAt(i);
					if (code1 == 14) 
					{
						var dropChar:String = str.charAt(i);
						var code2:int = str.charCodeAt(i+1);
						var newCode:int;
						
						if (isNaN(code2)) 
						{ 
							newCode = (code1 << 8)+13;
						} 
						else 
						{
							i++;
							cursor--;
							dropChar += str.charAt(i);
							
							if (code2 == 13) 
							{ 
								newCode = (code1 << 8)+10;
							} 
							else 
							{
								newCode = (code1 << 8)+code2;
							}
						}
						var newChar:String = String.fromCharCode(newCode);
						var tempArray:Array = str.split(dropChar);
						str = tempArray.join(newChar);
					}
				}
			}
			ti.text = str;
			ti.setSelection(cursor,cursor);
		}
	}
}